package com.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.example.easyexcel.pojo.Student;
import com.example.easyexcel.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;

@Slf4j
@Component
@Scope("prototype")
public class UploadDataListener extends AnalysisEventListener<Student> {

    @Autowired
    private StudentService studentService;


    ArrayList<Student> students = new ArrayList<>();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        Map<Integer, String> head;
    }

    @Override

        public void invoke(Student student, AnalysisContext analysisContext) {

        ReadSheetHolder readSheetHolder = analysisContext.readSheetHolder();
        String sheetName = readSheetHolder.getSheetName();
        students.add(student);
        if (students.size()>= 5){
            saveData(students,sheetName);
            students.clear();
        }
        log.info(""+students.size());
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData(students,analysisContext.readSheetHolder().getSheetName());
        log.info("所有数据解析完成！");
    }

    private void saveData(ArrayList<Student> list,String sheetName) {
        log.info("{}条数据，开始存储数据库！", list.size());
        studentService.readExcel(students,sheetName);
        log.info("存储数据库成功！");
    }
}
